package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.User;
import com.shop.mapper.UserMapper;
import com.shop.service.UserService;
import com.shop.service.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 新增用户
     *
     * @param user 用户
     * @return 影响行数
     */
    @Override
    public int saveNewUser(User user) {
        User newUser = new User();
        newUser.setUsername(user.getUsername()).setEmail(user.getEmail());
        newUser.setPassword(MD5Util.md5(user.getPassword()));
        return userMapper.insert(newUser);
    }
    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录成功的用户
     */
    @Override
    public User login(String username, String password) {

        if (StringUtils.isEmpty(username)){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return null;
        }
        if (!user.getPassword().equals(MD5Util.md5(password))){
            return null;
        }
        return user;
    }
    /**
     * 获取用户信息
     *
     * @param username 用户名
     * @return 用户
     */
    @Override
    public User getUser(String username){
        if (StringUtils.isEmpty(username)){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

}
